import axios from 'axios'
import Qs from 'qs'

export default async(url = '',data = {},type='GET',method='axios') => {
    type = type.toUpperCase();

    if(type == 'GET'){
        let dataStr = '';
        Object.keys(data).forEach(key=>{
            dataStr += key + '=' + data[key] + '&';
        })

        if(dataStr !== ''){
            dataStr = dataStr.substr(0,dataStr.lastIndexOf('&'));
            url += '?' + dataStr;
        }
    }

    if (method == 'axios') {
		let requestConfig = {
			// credentials: 'include',
			method: type,
			headers: {
			// 	'Accept': 'application/json',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			// mode: "cors",
			// cache: "force-cache",
		}

		if (type == 'POST') {
			requestConfig['data'] = Qs.stringify(data)
		}
		
		try {
			// //console.log(requestConfig)
			// console.log(url)
			const response =  await axios(url, requestConfig);
			// const responseJson = await response.json();
			return type == 'POST'?response['data']:response.data
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object') {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}